<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="工单ID" prop="ticket_id">
        <el-input
          v-model="queryParams.ticket_id"
          placeholder="请输入工单ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-180px"
        />
      </el-form-item>
      <el-form-item label="售后类型" prop="ticket_type">
        <el-select
          v-model="queryParams.ticket_type"
          placeholder="请选择售后类型"
          clearable
          class="!w-180px"
        >
          <el-option
            v-for="item in ticketTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- 添加分配人员搜索项 -->
      <el-form-item label="分配人员" prop="assigned_person">
        <el-select
          v-model="queryParams.assigned_person"
          placeholder="请选择分配人员"
          clearable
          class="!w-180px"
        >
          <el-option
            v-for="person in assignedPersonOptions"
            :key="person.value"
            :label="person.label"
            :value="person.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="来源渠道" prop="source">
        <el-select
          v-model="queryParams.source"
          placeholder="请选择来源渠道"
          clearable
          class="!w-180px"
        >
          <el-option
            v-for="item in sourceOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="当前状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择当前状态"
          clearable
          class="!w-180px"
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select
          v-model="queryParams.priority"
          placeholder="请选择优先级"
          clearable
          class="!w-180px"
        >
          <el-option
            v-for="item in priorityOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户名称" prop="customer_name">
        <el-input
          v-model="queryParams.customer_name"
          placeholder="请输入客户名称"
          clearable
          class="!w-180px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="create_time">
        <el-date-picker
          v-model="queryParams.create_time"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <el-button type="primary" plain @click="openForm('create')">
          <Icon icon="ep:plus" class="mr-5px" /> 新增工单
        </el-button>
        <!-- <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button> -->
        <el-button link type="primary" @click="okdialog">
          满意度调查
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="paginatedList"
      :stripe="true"
      :show-overflow-tooltip="true"
    >
      <el-table-column
        label="工单ID"
        align="center"
        prop="ticket_id"
        width="100"
      />
      <!-- 添加分配人员列 -->
      <el-table-column
        label="分配人员"
        align="center"
        prop="assigned_person"
        width="120"
      />

      <el-table-column
        label="售后类型"
        align="center"
        prop="ticket_type"
        width="100"
      >
        <template #default="{ row }">
          <!-- <el-tag :type="row.ticket_type === '售后' ? 'success' : 'primary'">
            {{ row.ticket_type }}
          </el-tag> -->
          {{ row.ticket_type }}
        </template>
      </el-table-column>
      <el-table-column
        label="机器人类型"
        align="center"
        prop="robot_type"
        width="150"
      >
        <template #default="{ row }">
          <el-tag :type="robotTypeTagType[row.robot_type]">
            {{ robotTypeMap[row.robot_type] || row.robot_type }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="来源渠道"
        align="center"
        prop="source"
        width="120"
      >
        <template #default="{ row }">
          {{ sourceMap[row.source] || row.source }}
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="create_time"
        :formatter="dateFormatter"
        width="160"
      />
      <el-table-column
        label="更新时间"
        align="center"
        prop="update_time"
        :formatter="dateFormatter"
        width="160"
      />
      <el-table-column
        label="当前状态"
        align="center"
        prop="status"
        width="120"
      >
        <template #default="{ row }">
          <el-tag :type="statusTagType[row.status]">
            {{ statusMap[row.status] || row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="优先级" align="center" prop="priority" width="80">
        <template #default="{ row }">
          <el-tag :type="priorityTagType[row.priority]">
            {{ row.priority }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="客户名称"
        align="center"
        prop="customer_name"
        width="150"
      />
      <el-table-column
        label="联系人"
        align="center"
        prop="contact_person"
        width="120"
      />
      <el-table-column
        label="联系方式"
        align="center"
        prop="contact_info"
        width="120"
      />
      <el-table-column
        label="问题描述"
        align="left"
        prop="description"
        min-width="200"
      />
      <el-table-column label="操作" align="center" width="180" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.ticket_id)"
          >
            编辑
          </el-button>
          <el-button link type="info" @click="openDetail(scope.row.ticket_id)">
            详情
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.ticket_id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="filteredTotal"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗 -->
  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      class="form-grid"
    >
      <el-form-item
        label="工单ID"
        prop="ticket_id"
        v-if="formType === 'update'"
      >
        <el-input v-model="formData.ticket_id" disabled />
      </el-form-item>
      <el-form-item label="售后类型" prop="ticket_type">
        <el-select v-model="formData.ticket_type" placeholder="请选择售后类型">
          <el-option
            v-for="item in ticketTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="机器人类型" prop="robot_type">
        <el-select v-model="formData.robot_type" placeholder="请选择机器人类型">
          <el-option
            v-for="item in robotTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="分配人员" prop="assigned_person">
        <el-select
          v-model="formData.assigned_person"
          placeholder="请选择分配人员"
        >
          <el-option
            v-for="person in assignedPersonOptions"
            :key="person.value"
            :label="person.label"
            :value="person.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="来源渠道" prop="source">
        <el-select v-model="formData.source" placeholder="请选择来源渠道">
          <el-option
            v-for="item in sourceOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="当前状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择当前状态">
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select v-model="formData.priority" placeholder="请选择优先级">
          <el-option
            v-for="item in priorityOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备ID" prop="device_id">
        <el-input v-model="formData.device_id" placeholder="请输入设备ID" />
      </el-form-item>
      <el-form-item label="设备序列号" prop="serial_number">
        <el-input
          v-model="formData.serial_number"
          placeholder="请输入设备序列号"
        />
      </el-form-item>
      <el-form-item label="问题分类" prop="category">
        <el-input v-model="formData.category" placeholder="请输入问题分类" />
      </el-form-item>
      <el-form-item label="问题描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入问题描述"
        />
      </el-form-item>
      <el-form-item label="客户ID" prop="customer_id">
        <el-input v-model="formData.customer_id" placeholder="请输入客户ID" />
      </el-form-item>
      <el-form-item label="客户名称" prop="customer_name">
        <el-input
          v-model="formData.customer_name"
          placeholder="请输入客户名称"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="contact_person">
        <el-input
          v-model="formData.contact_person"
          placeholder="请输入联系人"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="contact_info">
        <el-input
          v-model="formData.contact_info"
          placeholder="请输入联系方式"
        />
      </el-form-item>
      <el-form-item label="产品型号" prop="product_model">
        <el-input
          v-model="formData.product_model"
          placeholder="请输入产品型号"
        />
      </el-form-item>
      <el-form-item label="购买日期" prop="purchase_date">
        <el-date-picker
          v-model="formData.purchase_date"
          type="date"
          placeholder="选择购买日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="保修状态" prop="warranty_status">
        <el-select
          v-model="formData.warranty_status"
          placeholder="请选择保修状态"
        >
          <el-option label="在保" value="在保" />
          <el-option label="过保" value="过保" />
        </el-select>
      </el-form-item>
      <el-form-item label="保修截止日期" prop="warranty_expiry">
        <el-date-picker
          v-model="formData.warranty_expiry"
          type="date"
          placeholder="选择保修截止日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </template>
  </el-dialog>

  <!-- 详情弹窗 -->
  <el-dialog title="工单详情" v-model="detailVisible" width="800px">
    <el-descriptions :column="2" border>
      <el-descriptions-item label="工单ID">{{
        detailData.ticket_id
      }}</el-descriptions-item>
      <el-descriptions-item label="售后类型">
        <!-- <el-tag
          :type="detailData.ticket_type === '售后' ? 'success' : 'primary'"
        >
          {{ detailData.ticket_type }}
        </el-tag> -->
        {{ detailData.ticket_type }}
      </el-descriptions-item>
      <!-- 其他描述项... -->
      <el-descriptions-item label="机器人类型">
        <el-tag :type="robotTypeTagType[detailData.robot_type]">
          {{ robotTypeMap[detailData.robot_type] || detailData.robot_type }}
        </el-tag>
      </el-descriptions-item>

      <!-- 添加分配人员描述项 -->
      <el-descriptions-item label="分配人员">
        {{ detailData.assigned_person }}
      </el-descriptions-item>
      <el-descriptions-item label="来源渠道">
        {{ sourceMap[detailData.source] || detailData.source }}
      </el-descriptions-item>

      <el-descriptions-item label="当前状态">
        <el-tag :type="statusTagType[detailData.status]">
          {{ statusMap[detailData.status] || detailData.status }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="优先级">
        <el-tag :type="priorityTagType[detailData.priority]">
          {{ detailData.priority }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="设备ID">{{
        detailData.device_id
      }}</el-descriptions-item>
      <el-descriptions-item label="设备序列号">{{
        detailData.serial_number
      }}</el-descriptions-item>
      <el-descriptions-item label="问题分类">{{
        detailData.category
      }}</el-descriptions-item>
      <el-descriptions-item label="客户ID">{{
        detailData.customer_id
      }}</el-descriptions-item>
      <el-descriptions-item label="客户名称">{{
        detailData.customer_name
      }}</el-descriptions-item>
      <el-descriptions-item label="联系人">{{
        detailData.contact_person
      }}</el-descriptions-item>
      <el-descriptions-item label="联系方式">{{
        detailData.contact_info
      }}</el-descriptions-item>
      <el-descriptions-item label="产品型号">{{
        detailData.product_model
      }}</el-descriptions-item>
      <el-descriptions-item label="购买日期">{{
        detailData.purchase_date
      }}</el-descriptions-item>
      <el-descriptions-item label="保修状态">
        <el-tag
          :type="detailData.warranty_status === '在保' ? 'success' : 'danger'"
        >
          {{ detailData.warranty_status }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="保修截止日期">{{
        detailData.warranty_expiry
      }}</el-descriptions-item>
      <el-descriptions-item label="问题描述" :span="2">
        {{ detailData.description }}
      </el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <el-button type="primary" @click="detailVisible = false">关 闭</el-button>
    </template>
  </el-dialog>
  <el-dialog v-model="dialog" fullscreen @closa="dialogclosa">
    <!-- 添加外层容器实现居中布局 -->
    <div class="fullscreen-dialog-container">
      <el-form
        :model="form"
        ref="surveyForm"
        class="centered-form"
        label-position="top"
        :rules="rules"
      >
        <!-- 第一部分：产品验收评估 -->
        <div class="form-section">
          <h3 class="section-title">产品验收评估</h3>

          <!-- 功能完整性 -->
          <el-form-item label="功能完整性" prop="acceptance.functionality">
            <div class="acceptance-item">
              <p class="acceptance-standard">
                验收标准：所有功能模块正常运行，符合产品说明要求
              </p>
              <el-radio-group v-model="form.acceptance.functionality">
                <el-radio label="pass">通过</el-radio>
                <el-radio label="fail">未通过</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>

          <!-- 性能稳定性 -->
          <el-form-item label="性能稳定性" prop="acceptance.performance">
            <div class="acceptance-item">
              <p class="acceptance-standard">
                验收标准：无卡顿、崩溃或数据丢失，响应速度≤3秒
              </p>
              <el-radio-group v-model="form.acceptance.performance">
                <el-radio label="pass">通过</el-radio>
                <el-radio label="fail">未通过</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>

          <!-- 使用体验 -->
          <el-form-item label="使用体验" prop="acceptance.experience">
            <div class="acceptance-item">
              <p class="acceptance-standard">
                验收标准：界面简洁、操作流畅，提示信息明确
              </p>
              <el-radio-group v-model="form.acceptance.experience">
                <el-radio label="pass">通过</el-radio>
                <el-radio label="fail">未通过</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>

          <!-- 安全性 -->
          <el-form-item label="安全性" prop="acceptance.security">
            <div class="acceptance-item">
              <p class="acceptance-standard">
                验收标准：无隐私泄露风险，数据加密可靠（参考行业安全标准）
              </p>
              <el-radio-group v-model="form.acceptance.security">
                <el-radio label="pass">通过</el-radio>
                <el-radio label="fail">未通过</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>

          <!-- 文档完整性 -->
          <el-form-item label="文档完整性" prop="acceptance.documentation">
            <div class="acceptance-item">
              <p class="acceptance-standard">
                验收标准：提供用户手册、保修条款及应急联系方式
              </p>
              <el-radio-group v-model="form.acceptance.documentation">
                <el-radio label="pass">通过</el-radio>
                <el-radio label="fail">未通过</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>

          <!-- 未通过说明 -->
          <el-form-item
            label="未通过说明 （请标注具体项目及问题）"
            prop="acceptance.failureReason"
            class="failure-reason"
          >
            <el-input
              v-model="form.acceptance.failureReason"
              type="textarea"
              :rows="3"
              placeholder="请详细说明未通过的项目及具体问题"
            />
          </el-form-item>
        </div>

        <!-- 第二部分：满意度调查 -->
        <div class="form-section">
          <h3 class="section-title">满意度调查（5=非常满意，1=非常不满意）</h3>

          <!-- 产品质量 - 功能实用性 -->
          <el-form-item
            label="产品质量 - 功能实用性"
            prop="satisfaction.functionUsefulness"
          >
            <div class="satisfaction-item">
              <el-rate
                v-model="form.satisfaction.functionUsefulness"
                :max="5"
                :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                show-score
                score-template="{value}分"
              />
              <el-input
                v-if="form.satisfaction.functionUsefulness <= 3"
                v-model="form.satisfaction.functionUsefulnessComment"
                type="textarea"
                :rows="2"
                placeholder="请说明原因（评分≤3分需填写）"
                class="reason-input"
              />
            </div>
          </el-form-item>

          <!-- 产品质量 - 耐用性/稳定性 -->
          <el-form-item
            label="产品质量 - 耐用性/稳定性"
            prop="satisfaction.durability"
          >
            <div class="satisfaction-item">
              <el-rate
                v-model="form.satisfaction.durability"
                :max="5"
                :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                show-score
                score-template="{value}分"
              />
              <el-input
                v-if="form.satisfaction.durability <= 3"
                v-model="form.satisfaction.durabilityComment"
                type="textarea"
                :rows="2"
                placeholder="请说明原因（评分≤3分需填写）"
                class="reason-input"
              />
            </div>
          </el-form-item>

          <!-- 服务体验 - 售前咨询专业性 -->
          <el-form-item
            label="服务体验 - 售前咨询专业性"
            prop="satisfaction.preSales"
          >
            <div class="satisfaction-item">
              <el-rate
                v-model="form.satisfaction.preSales"
                :max="5"
                :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                show-score
                score-template="{value}分"
              />
              <el-input
                v-if="form.satisfaction.preSales <= 3"
                v-model="form.satisfaction.preSalesComment"
                type="textarea"
                :rows="2"
                placeholder="请说明原因（评分≤3分需填写）"
                class="reason-input"
              />
            </div>
          </el-form-item>

          <!-- 服务体验 - 售后响应速度 -->
          <el-form-item
            label="服务体验 - 售后响应速度"
            prop="satisfaction.afterSales"
          >
            <div class="satisfaction-item">
              <el-rate
                v-model="form.satisfaction.afterSales"
                :max="5"
                :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                show-score
                score-template="{value}分"
              />
              <el-input
                v-if="form.satisfaction.afterSales <= 3"
                v-model="form.satisfaction.afterSalesComment"
                type="textarea"
                :rows="2"
                placeholder="请说明原因（评分≤3分需填写）"
                class="reason-input"
              />
            </div>
          </el-form-item>

          <!-- 性价比 -->
          <el-form-item label="性价比" prop="satisfaction.valueForMoney">
            <div class="satisfaction-item">
              <el-rate
                v-model="form.satisfaction.valueForMoney"
                :max="5"
                :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                show-score
                score-template="{value}分"
              />
              <el-input
                v-if="form.satisfaction.valueForMoney <= 3"
                v-model="form.satisfaction.valueForMoneyComment"
                type="textarea"
                :rows="2"
                placeholder="请说明原因（评分≤3分需填写）"
                class="reason-input"
              />
            </div>
          </el-form-item>

          <!-- 品牌忠诚度 - 重复购买意愿 -->
          <el-form-item
            label="品牌忠诚度 - 重复购买意愿"
            prop="satisfaction.repurchase"
          >
            <div class="satisfaction-item">
              <el-rate
                v-model="form.satisfaction.repurchase"
                :max="5"
                :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                show-score
                score-template="{value}分"
              />
              <el-input
                v-if="form.satisfaction.repurchase <= 3"
                v-model="form.satisfaction.repurchaseComment"
                type="textarea"
                :rows="2"
                placeholder="请说明原因（评分≤3分需填写）"
                class="reason-input"
              />
            </div>
          </el-form-item>
        </div>

        <!-- 第三部分：补充调查 -->
        <div class="form-section">
          <h3 class="section-title">补充调查</h3>

          <!-- 总体满意度 -->
          <el-form-item
            label="总体满意度"
            prop="supplement.overallSatisfaction"
          >
            <el-rate
              v-model="form.supplement.overallSatisfaction"
              :max="5"
              show-score
              :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
            />
          </el-form-item>

          <!-- 是否再次使用 -->
          <el-form-item label="是否再次使用" prop="supplement.reuse">
            <el-radio-group v-model="form.supplement.reuse">
              <el-radio label="yes">是</el-radio>
              <el-radio label="no">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 改进建议 -->
          <el-form-item label="改进建议" prop="supplement.suggestions">
            <el-checkbox-group v-model="form.supplement.suggestions">
              <el-checkbox label="ui">界面优化</el-checkbox>
              <el-checkbox label="speed">提高速度</el-checkbox>
              <el-checkbox label="feature">增加功能</el-checkbox>
              <el-checkbox label="price">价格调整</el-checkbox>
              <el-checkbox label="service">服务改进</el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <!-- 详细意见 -->
          <el-form-item label="其他建议" prop="supplement.comments">
            <el-input
              v-model="form.supplement.comments"
              type="textarea"
              :rows="5"
              placeholder="请分享您的其他建议或使用体验"
            />
          </el-form-item>
        </div>

        <el-form-item class="submit-btn-container">
          <el-button type="primary" @click="submitSurvey" size="large"
            >提交评估</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { dateFormatter } from "@/utils/formatTime";
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
defineOptions({ name: "AfterSaleTicket" });
import { useUserStoreWithOut } from "@/store/modules/user";
const userStore = useUserStoreWithOut(); // 用户信息缓存
const { t } = useI18n();
const message = useMessage();

// 列表相关状态
const loading = ref(true);
const ticketList = ref([]);
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  ticket_id: undefined,
  ticket_type: undefined,
  source: undefined,
  status: undefined,
  priority: undefined,
  customer_name: undefined,
  create_time: [],
  assigned_person: undefined,
});
// 添加分配人员选项
const assignedPersonOptions = [
  { value: "yunwei001", label: "yunwei001" },
  { value: "yunwei002", label: "yunwei002" },
];
const queryFormRef = ref();
// const exportLoading = ref(false);
//----- 问卷调查相关
const rules = reactive({
  // 验收部分规则
  "acceptance.functionality": [
    { required: true, message: "请选择功能完整性评估", trigger: "change" },
  ],
  "acceptance.performance": [
    { required: true, message: "请选择性能稳定性评估", trigger: "change" },
  ],
  "acceptance.experience": [
    { required: true, message: "请选择使用体验评估", trigger: "change" },
  ],
  "acceptance.security": [
    { required: true, message: "请选择安全性评估", trigger: "change" },
  ],
  "acceptance.documentation": [
    { required: true, message: "请选择文档完整性评估", trigger: "change" },
  ],

  // 满意度部分规则
  "satisfaction.functionUsefulness": [
    { required: true, message: "请对功能实用性进行评分", trigger: "change" },
  ],
  "satisfaction.durability": [
    { required: true, message: "请对耐用性/稳定性进行评分", trigger: "change" },
  ],
  "satisfaction.preSales": [
    {
      required: true,
      message: "请对售前咨询专业性进行评分",
      trigger: "change",
    },
  ],
  "satisfaction.afterSales": [
    { required: true, message: "请对售后响应速度进行评分", trigger: "change" },
  ],
  "satisfaction.valueForMoney": [
    { required: true, message: "请对性价比进行评分", trigger: "change" },
  ],
  "satisfaction.repurchase": [
    { required: true, message: "请对重复购买意愿进行评分", trigger: "change" },
  ],

  // 补充调查部分规则
  "supplement.overallSatisfaction": [
    { required: true, message: "请选择总体满意度", trigger: "change" },
  ],
  "supplement.reuse": [
    { required: true, message: "请选择是否再次使用", trigger: "change" },
  ],
  "supplement.suggestions": [
    {
      type: "array",
      required: true,
      message: "请至少选择一项改进建议",
      trigger: "change",
    },
  ],
  commentRules: [
    { required: true, message: "请填写评分原因", trigger: "blur" },
  ],
});
const dialog = ref(false);
const okdialog = () => {
  dialog.value = true;
  surveyForm.value.resetFields();
};
const dialogclosa = () => {
  dialog.value = false;
  form.value = {};
};
// 表单数据结构
const form = ref({
  acceptance: {
    functionality: "",
    performance: "",
    experience: "",
    security: "",
    documentation: "",
    failureReason: "",
  },
  satisfaction: {
    functionUsefulness: 0,
    functionUsefulnessComment: "",
    durability: 0,
    durabilityComment: "",
    preSales: 0,
    preSalesComment: "",
    afterSales: 0,
    afterSalesComment: "",
    valueForMoney: 0,
    valueForMoneyComment: "",
    repurchase: 0,
    repurchaseComment: "",
  },
  supplement: {
    overallSatisfaction: 0,
    reuse: "",
    suggestions: [],
    comments: "",
  },
});
const surveyForm = ref();
// 提交调查
const submitSurvey = async () => {
  surveyForm.value.validate((valid: any) => {
    if (valid) {
      // 添加时间戳
      const result = {
        ...form.value,
        nickname: userStore.user.nickname,
        userId: userStore.user.id, // 添加用户ID标识
        timestamp: new Date().toLocaleString(),
      };

      // 使用用户专属的存储键名
      const USER_STORAGE_KEY = `SURVEY_RESULTS_${userStore.user.id}`;

      // 获取该用户的历史数据
      const storedData = localStorage.getItem(USER_STORAGE_KEY);
      const userSurveyData = storedData ? JSON.parse(storedData) : [];

      // 添加新数据到用户专属数组
      userSurveyData.push(result);

      // 保存用户专属数据
      localStorage.setItem(USER_STORAGE_KEY, JSON.stringify(userSurveyData));

      // 重置表单
      form.value = {
        acceptance: {
          functionality: "",
          performance: "",
          experience: "",
          security: "",
          documentation: "",
          failureReason: "",
        },
        satisfaction: {
          functionUsefulness: 0,
          functionUsefulnessComment: "",
          durability: 0,
          durabilityComment: "",
          preSales: 0,
          preSalesComment: "",
          afterSales: 0,
          afterSalesComment: "",
          valueForMoney: 0,
          valueForMoneyComment: "",
          repurchase: 0,
          repurchaseComment: "",
        },
        supplement: {
          overallSatisfaction: 0,
          reuse: "",
          suggestions: [],
          comments: "",
        },
      };

      ElMessage.success("提交成功！");
      surveyForm.value.resetFields();
      dialog.value = false;
    }
  });
};

// -----
// 弹窗相关状态
const dialogVisible = ref(false);
const detailVisible = ref(false);
const dialogTitle = ref("");
const formType = ref(""); // 'create' | 'update'
const formData = ref({
  ticket_id: undefined,
  ticket_type: "售后",
  source: "电话",
  create_time: undefined,
  update_time: undefined,
  status: "待分配",
  priority: "P2",
  device_id: "",
  serial_number: "",
  category: "",
  description: "",
  customer_id: "",
  customer_name: "",
  contact_person: "",
  contact_info: "",
  product_model: "",
  purchase_date: "",
  warranty_status: "在保",
  warranty_expiry: "",
  assigned_person: "",
});
const detailData = ref({});
const formRef = ref();
const formRules = reactive({
  ticket_type: [
    { required: true, message: "售后类型不能为空", trigger: "change" },
  ],
  robot_type: [
    { required: true, message: "机器人类型不能为空", trigger: "change" },
  ],
  source: [{ required: true, message: "来源渠道不能为空", trigger: "change" }],
  status: [{ required: true, message: "当前状态不能为空", trigger: "change" }],
  priority: [{ required: true, message: "优先级不能为空", trigger: "change" }],
  description: [
    { required: true, message: "问题描述不能为空", trigger: "blur" },
  ],
  customer_name: [
    { required: true, message: "客户名称不能为空", trigger: "blur" },
  ],
  contact_person: [
    { required: true, message: "联系人不能为空", trigger: "blur" },
  ],
  contact_info: [
    { required: true, message: "联系方式不能为空", trigger: "blur" },
  ],
});

// 下拉选项
const ticketTypeOptions = [
  { value: "维修服务", label: "维修服务" },
  { value: "退换货", label: "退换货" },
  { value: "安装调试", label: "安装调试" },
  { value: "技术咨询", label: "技术咨询" },
  { value: "配件更换", label: "配件更换" },
  { value: "产品升级", label: "产品升级" },
  { value: "保修服务", label: "保修服务" },
  { value: "投诉处理", label: "投诉处理" },
  { value: "其他售后", label: "其他售后" },
];

const sourceOptions = [
  { value: "电话", label: "电话" },
  { value: "邮件", label: "邮件" },
  { value: "APP", label: "APP" },
  { value: "微信", label: "微信" },
];

const statusOptions = [
  { value: "待分配", label: "待分配" },
  { value: "已分配", label: "已分配" },
  { value: "处理中", label: "处理中" },
  { value: "待确认", label: "待确认" },
  { value: "已完成", label: "已完成" },
  { value: "已关闭", label: "已关闭" },
  { value: "已取消", label: "已取消" },
];

const priorityOptions = [
  { value: "P0", label: "P0 (最高)" },
  { value: "P1", label: "P1 (高)" },
  { value: "P2", label: "P2 (中)" },
  { value: "P3", label: "P3 (低)" },
  { value: "P4", label: "P4 (最低)" },
];

// 映射关系
const sourceMap = {
  电话: "电话",
  邮件: "邮件",
  系统上报: "系统上报",
  APP: "APP",
  微信: "微信",
};

const statusMap = {
  待分配: "待分配",
  已分配: "已分配",
  处理中: "处理中",
  待确认: "待确认",
  已完成: "已完成",
  已关闭: "已关闭",
  已取消: "已取消",
};

// 标签类型映射
const statusTagType = {
  待分配: "info",
  已分配: "",
  处理中: "warning",
  待确认: "primary",
  已完成: "success",
  已关闭: "danger",
  已取消: "danger",
};

const priorityTagType = {
  P0: "danger",
  P1: "warning",
  P2: "",
  P3: "primary",
  P4: "success",
};
// 机器人类型选项
const robotTypeOptions = [
  { value: "guide", label: "智能导览机器人" },
  { value: "inventory", label: "智能盘点机器人" },
  { value: "return", label: "智能还书系统" },
];

// 机器人类型映射
const robotTypeMap = {
  guide: "智能导览机器人",
  inventory: "智能盘点机器人",
  return: "智能还书系统",
};

// 机器人类型标签样式
const robotTypeTagType = {
  guide: "success",
  inventory: "warning",
  return: "primary",
};
// 初始化本地数据
const initLocalData = () => {
  if (userStore.user.nickname == "超级管理员") {
    ticketList.value = [
      {
        ticket_id: "T20230710001",
        ticket_type: "维修服务",
        robot_type: "guide", // 智能导览机器人
        source: "电话",
        create_time: "2025-02-10 09:25:30",
        update_time: "2025-06-10 14:30:45",
        status: "处理中",
        priority: "P1",
        device_id: "DEV-1001",
        serial_number: "SN-20230710001",
        category: "硬件故障/主板",
        description: "设备频繁死机，需要更换主板",
        customer_id: "C1001",
        customer_name: "上海科技公司",
        contact_person: "张经理",
        contact_info: "13800138001",
        product_model: "PRO-5000",
        purchase_date: "2022-05-15",
        warranty_status: "在保",
        warranty_expiry: "2024-05-15",
        assigned_person: "yunwei001", // 添加分配人员
      },
      {
        ticket_id: "T20230710002",
        ticket_type: "退换货",
        robot_type: "return", // 智能还书系统
        source: "电话",
        create_time: "2025-01-10 10:15:22",
        update_time: "2023-05-10 10:30:18",
        status: "处理中",
        priority: "P2",
        device_id: "DEV-1002",
        serial_number: "SN-20230710002",
        category: "软件问题/系统升级",
        description: "系统需要升级到最新版本",
        customer_id: "C1002",
        customer_name: "上海科技公司",
        contact_person: "张经理",
        contact_info: "13800138001",
        product_model: "PRO-6000",
        purchase_date: "2021-12-10",
        warranty_status: "过保",
        warranty_expiry: "2023-01-10",
        assigned_person: "yunwei001", // 添加分配人员
      },
      {
        ticket_id: "T20230710003",
        ticket_type: "安装调试",
        robot_type: "inventory", // 智能盘点机器人
        source: "APP",
        create_time: "2024-07-09 14:30:45",
        update_time: "2024-12-10 09:15:30",
        status: "已完成",
        priority: "P3",
        device_id: "DEV-1003",
        serial_number: "SN-20230710003",
        category: "网络问题/连接故障",
        description: "设备无法连接到网络，需要技术支持",
        customer_id: "C1003",
        customer_name: "上海科技公司",
        contact_person: "张经理",
        contact_info: "13800138001",
        product_model: "PRO-4000",
        purchase_date: "2022-08-20",
        warranty_status: "在保",
        warranty_expiry: "2024-08-20",
        assigned_person: "yunwei001", // 添加分配人员
      },
      {
        ticket_id: "T20230710004",
        ticket_type: "技术咨询",
        robot_type: "inventory", // 智能盘点机器人
        source: "微信",
        create_time: "2025-03-08 16:45:12",
        update_time: "2025-07-10 11:20:33",
        status: "处理中",
        priority: "P4",
        device_id: "DEV-1004",
        serial_number: "SN-20230710004",
        category: "配置问题/参数设置",
        description: "需要协助配置设备参数",
        customer_id: "C1004",
        customer_name: "深圳智能公司",
        contact_person: "赵工程师",
        contact_info: "13600136004",
        product_model: "PRO-7000",
        purchase_date: "2020-10-05",
        warranty_status: "过保",
        warranty_expiry: "2022-10-05",
        assigned_person: "yunwei002", // 添加分配人员
      },
      {
        ticket_id: "T20230710005",
        ticket_type: "产品升级",
        robot_type: "inventory", // 智能盘点机器人
        source: "邮件",
        create_time: "2024-04-10 13:05:18",
        update_time: "2023-05-10 13:05:18",
        status: "已完成",
        priority: "P2",
        device_id: "DEV-1005",
        serial_number: "SN-20230710005",
        category: "性能问题/响应缓慢",
        description: "设备响应速度慢，需要优化",
        customer_id: "C1005",
        customer_name: "深圳智能公司",
        contact_person: "赵工程师",
        contact_info: "13600136004",
        product_model: "PRO-8000",
        purchase_date: "2023-01-12",
        warranty_status: "在保",
        warranty_expiry: "2025-01-12",
        assigned_person: "yunwei002", // 添加分配人员
      },
    ];
  }
  if (
    userStore.user.nickname == "kehu002" ||
    userStore.user.nickname == "yunwei002"
  ) {
    ticketList.value = [
      {
        ticket_id: "T20230710004",
        ticket_type: "技术咨询",
        robot_type: "inventory", // 智能盘点机器人
        source: "微信",
        create_time: "2025-03-08 16:45:12",
        update_time: "2025-07-10 11:20:33",
        status: "处理中",
        priority: "P4",
        device_id: "DEV-1004",
        serial_number: "SN-20230710004",
        category: "配置问题/参数设置",
        description: "需要协助配置设备参数",
        customer_id: "C1004",
        customer_name: "深圳智能公司",
        contact_person: "赵工程师",
        contact_info: "13600136004",
        product_model: "PRO-7000",
        purchase_date: "2020-10-05",
        warranty_status: "过保",
        warranty_expiry: "2022-10-05",
        assigned_person: "yunwei002", // 添加分配人员
      },
      {
        ticket_id: "T20230710005",
        ticket_type: "产品升级",
        robot_type: "inventory", // 智能盘点机器人
        source: "邮件",
        create_time: "2024-04-10 13:05:18",
        update_time: "2023-05-10 13:05:18",
        status: "已完成",
        priority: "P2",
        device_id: "DEV-1005",
        serial_number: "SN-20230710005",
        category: "性能问题/响应缓慢",
        description: "设备响应速度慢，需要优化",
        customer_id: "C1005",
        customer_name: "深圳智能公司",
        contact_person: "赵工程师",
        contact_info: "13600136004",
        product_model: "PRO-8000",
        purchase_date: "2023-01-12",
        warranty_status: "在保",
        warranty_expiry: "2025-01-12",
        assigned_person: "yunwei002", // 添加分配人员
      },
    ];
  }
  if (
    userStore.user.nickname == "kehu001" ||
    userStore.user.nickname == "yunwei001"
  ) {
    ticketList.value = [
      {
        ticket_id: "T20230710001",
        ticket_type: "维修服务",
        robot_type: "guide", // 智能导览机器人
        source: "电话",
        create_time: "2025-02-10 09:25:30",
        update_time: "2025-06-10 14:30:45",
        status: "处理中",
        priority: "P1",
        device_id: "DEV-1001",
        serial_number: "SN-20230710001",
        category: "硬件故障/主板",
        description: "设备频繁死机，需要更换主板",
        customer_id: "C1001",
        customer_name: "上海科技公司",
        contact_person: "张经理",
        contact_info: "13800138001",
        product_model: "PRO-5000",
        purchase_date: "2022-05-15",
        warranty_status: "在保",
        warranty_expiry: "2024-05-15",
        assigned_person: "yunwei001", // 添加分配人员
      },
      {
        ticket_id: "T20230710002",
        ticket_type: "退换货",
        robot_type: "return", // 智能还书系统
        source: "电话",
        create_time: "2025-01-10 10:15:22",
        update_time: "2023-05-10 10:30:18",
        status: "处理中",
        priority: "P2",
        device_id: "DEV-1002",
        serial_number: "SN-20230710002",
        category: "软件问题/系统升级",
        description: "系统需要升级到最新版本",
        customer_id: "C1002",
        customer_name: "上海科技公司",
        contact_person: "张经理",
        contact_info: "13900139002",
        product_model: "PRO-6000",
        purchase_date: "2021-12-10",
        warranty_status: "过保",
        warranty_expiry: "2023-01-10",
        assigned_person: "yunwei001", // 添加分配人员
      },
      {
        ticket_id: "T20230710003",
        ticket_type: "安装调试",
        robot_type: "inventory", // 智能盘点机器人
        source: "APP",
        create_time: "2024-07-09 14:30:45",
        update_time: "2024-12-10 09:15:30",
        status: "已完成",
        priority: "P3",
        device_id: "DEV-1003",
        serial_number: "SN-20230710003",
        category: "网络问题/连接故障",
        description: "设备无法连接到网络，需要技术支持",
        customer_id: "C1003",
        customer_name: "上海科技公司",
        contact_person: "张经理",
        contact_info: "13700137003",
        product_model: "PRO-4000",
        purchase_date: "2022-08-20",
        warranty_status: "在保",
        warranty_expiry: "2024-08-20",
        assigned_person: "yunwei001", // 添加分配人员
      },
    ];
  }
};

// 计算属性
const filteredList = computed(() => {
  let result = [...ticketList.value];

  // 工单ID筛选
  if (queryParams.ticket_id) {
    result = result.filter((item) =>
      item.ticket_id.includes(queryParams.ticket_id)
    );
  }

  // 售后类型筛选
  if (queryParams.ticket_type) {
    result = result.filter(
      (item) => item.ticket_type === queryParams.ticket_type
    );
  }

  // 来源渠道筛选
  if (queryParams.source) {
    result = result.filter((item) => item.source === queryParams.source);
  }

  // 状态筛选
  if (queryParams.status) {
    result = result.filter((item) => item.status === queryParams.status);
  }

  // 优先级筛选
  if (queryParams.priority) {
    result = result.filter((item) => item.priority === queryParams.priority);
  }

  // 客户名称筛选
  if (queryParams.customer_name) {
    result = result.filter((item) =>
      item.customer_name.includes(queryParams.customer_name)
    );
  }
  // 添加分配人员筛选
  if (queryParams.assigned_person) {
    result = result.filter(
      (item) => item.assigned_person === queryParams.assigned_person
    );
  }
  // 创建时间筛选
  if (queryParams.create_time?.length === 2) {
    const [start, end] = queryParams.create_time;
    result = result.filter((item) => {
      const time = new Date(item.create_time).getTime();
      return (
        time >= new Date(start).getTime() && time <= new Date(end).getTime()
      );
    });
  }

  // 按创建时间降序排序
  //result.sort((a, b) => new Date(b.create_time) - new Date(a.create_time));

  return result;
});

const paginatedList = computed(() => {
  const start = (queryParams.pageNo - 1) * queryParams.pageSize;
  const end = start + queryParams.pageSize;
  return filteredList.value.slice(start, end);
});

const filteredTotal = computed(() => filteredList.value.length);

// 方法
const getList = () => {
  loading.value = false; // 本地数据无需加载
  console.log(userStore.user.nickname);
};

const handleQuery = () => {
  queryParams.pageNo = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value.resetFields();
  queryParams.create_time = [];
  handleQuery();
};

const openForm = (type: string, id?: string) => {
  formType.value = type;
  dialogTitle.value = type === "create" ? "新增工单" : "编辑工单";
  dialogVisible.value = true;

  // 重置表单
  formData.value = {
    ticket_id: undefined,
    ticket_type: "",
    source: "电话",
    create_time: new Date().toISOString().replace("T", " ").substring(0, 19),
    update_time: new Date().toISOString().replace("T", " ").substring(0, 19),
    status: "待分配",
    priority: "P2",
    device_id: "",
    serial_number: "",
    category: "",
    description: "",
    customer_id: "",
    customer_name: "",
    contact_person: "",
    contact_info: "",
    product_model: "",
    purchase_date: "",
    warranty_status: "在保",
    warranty_expiry: "",
  };

  // 如果是编辑，填充数据
  if (id) {
    const ticket = ticketList.value.find((item) => item.ticket_id === id);
    if (ticket) {
      formData.value = { ...ticket };
    }
  }
};

const openDetail = (id: string) => {
  const ticket = ticketList.value.find((item) => item.ticket_id === id);
  if (ticket) {
    detailData.value = { ...ticket };
    detailVisible.value = true;
  }
};

const handleSubmit = async () => {
  try {
    await formRef.value.validate();

    // 生成工单ID（如果是新增）
    if (formType.value === "create") {
      // 生成新的工单ID
      const maxId = Math.max(
        ...ticketList.value.map((item) =>
          parseInt(item.ticket_id.replace("T", ""))
        ),
        20230710000
      );
      formData.value.ticket_id = `T${maxId + 1}`;
      formData.value.create_time = new Date()
        .toISOString()
        .replace("T", " ")
        .substring(0, 19);

      // 添加到列表开头
      //ticketList.value.unshift({ ...formData.value });
      ticketList.value.push({ ...formData.value });
      message.success("新增工单成功");
    } else {
      // 更新逻辑
      formData.value.update_time = new Date()
        .toISOString()
        .replace("T", " ")
        .substring(0, 19);
      const index = ticketList.value.findIndex(
        (item) => item.ticket_id === formData.value.ticket_id
      );
      if (index !== -1) {
        ticketList.value.splice(index, 1, formData.value);
      }
      message.success("更新工单成功");
    }

    dialogVisible.value = false;
    getList();
  } catch (e) {
    console.error("表单验证失败", e);
  }
};

const handleDelete = async (id: string) => {
  try {
    await message.delConfirm("确定删除该工单吗？");
    ticketList.value = ticketList.value.filter((item) => item.ticket_id !== id);
    message.success("删除工单成功");
    getList();
  } catch {}
};

// const handleExport = async () => {
//   try {
//     await message.exportConfirm();
//     exportLoading.value = true;
//     const data = JSON.stringify(filteredList.value, null, 2);
//     const blob = new Blob([data], { type: "application/json" });
//     const url = URL.createObjectURL(blob);
//     const link = document.createElement("a");
//     link.href = url;
//     link.download = "售后工单数据.json";
//     link.click();
//     URL.revokeObjectURL(url);
//     message.success("导出成功");
//   } finally {
//     exportLoading.value = false;
//   }
// };

// 初始化
onMounted(() => {
  initLocalData();
  getList();
});
</script>

<style scoped>
.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

@media (max-width: 768px) {
  .form-grid {
    grid-template-columns: 1fr;
  }
}

/* 全屏容器样式 */
.fullscreen-dialog-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fff;
}
</style>
